package com.syh.jn.scm.infrastructure.repository.impl.supplier.finance;

import cn.redscarf.commons.wrapper.Wrapper;
import com.syh.core.ddd.infrastructure.repository.AbstractAggregateRepository;
import com.syh.jn.scm.domain.supplier.entity.finance.BusinessAccountSummary;
import com.syh.jn.scm.domain.supplier.repository.finance.BusinessAccountSummaryRepository;
import com.syh.jn.scm.dto.supplier.finance.BusinessAccountSummaryVo;
import com.syh.jn.scm.infrastructure.repository.model.finance.BusinessAccountRecordModel;
import com.syh.jn.scm.infrastructure.repository.model.finance.BusinessAccountSummaryModel;
import com.syh.jn.scm.infrastructure.repository.utils.SQLAliasGenerateUtil;
import com.syh.jn.scm.infrastructure.wrapper.BaseResolve;
import com.syh.jn.scm.infrastructure.wrapper.ResolveToSQL;
import org.apache.ibatis.jdbc.SQL;
import org.springframework.stereotype.Repository;

import java.util.HashMap;
import java.util.Map;

/**
 * 单位应收付记录汇总表
 */
@Repository
public class BusinessAccountSummaryRepositoryImpl extends AbstractAggregateRepository<BusinessAccountSummary, BusinessAccountSummaryModel, Long> implements BusinessAccountSummaryRepository {
  @Override
  protected SQL getViewSql() {

    return new SQL(){{
      SELECT(
              SQLAliasGenerateUtil.aliasGenerate(BusinessAccountSummaryModel.class,"summary", null),
              "CONCAT(IFNULL(downstream.`NAME`, ''), IFNULL(logistics.`NAME`, ''), IFNULL(upstream.`NAME`, '')) AS name"
      );
      FROM("T_FINANCE_BUSINESS_ACCOUNT_SUMMARY AS summary");
      LEFT_OUTER_JOIN("T_BASE_DOWNSTREAM AS downstream ON summary.CUSTOMER_ID = downstream.ID AND summary.CUSTOMER_TYPE = 1");
      LEFT_OUTER_JOIN("T_BASE_UPSTREAM AS upstream ON summary.CUSTOMER_ID = upstream.ID AND summary.CUSTOMER_TYPE = 0");
      LEFT_OUTER_JOIN("T_BASE_LOGISTICS AS logistics ON summary.CUSTOMER_ID = logistics.ID AND summary.CUSTOMER_TYPE = 2");
    }};
  }

  @Override
  protected BaseResolve getViewWrapperResolve(Wrapper wrapper) {
    Map<String,String> map = new HashMap<>();
    map.put("id","summary.ID");
    map.put("customerId","summary.CUSTOMER_ID");
    map.put("customerType","summary.CUSTOMER_TYPE");
    map.put("businessEntityId", "summary.BUSINESS_ENTITY_ID");

    ResolveToSQL parse = new ResolveToSQL(wrapper, (propertyName) -> {
      return map.get(propertyName);
    });
    return parse;
  }

  @Override
  protected Class getViewObject() {
    return BusinessAccountSummaryVo.class;
  }
}
